package com.lab303.powerproject.util;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.SocketException;

public class FtpUtil {

    private static final Logger LOG = LoggerFactory.getLogger(FtpUtil.class);

    public static FTPClient getFTPClient(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) {
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                LOG.info("未连接到FTP，用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                LOG.info("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            LOG.info("FTP的IP地址可能错误，请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            LOG.info("FTP的端口错误,请正确配置。");
        }
        return ftpClient;
    }


    /**
     * Description: 向FTP服务器上传文件
     * @param basePath FTP服务器基础目录
     * @param filePath FTP服务器文件存放路径。例如分日期存放：/2015/01/01。文件的路径为basePath+filePath
     * @param filename 上传到FTP服务器上的文件名
     * @param input 输入流
     * @return 成功返回true，否则返回false
     */
    public static boolean uploadFile(FTPClient ftp,String basePath,String filePath, String filename, InputStream input) {
        boolean result = false;
        try {
            //切换到上传目录
            if (!ftp.changeWorkingDirectory(basePath+filePath)) {
                //如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                String tempPath = basePath;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            return result;
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            //设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.setControlEncoding("UTF-8");
            ftp.enterLocalPassiveMode();
            ftp.setBufferSize(4*1024*1024);
            BufferedInputStream inputStream = new BufferedInputStream(input);
            //上传文件
            if (!ftp.storeFile(filename, inputStream)) {
                return result;
            }
            input.close();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        return result;
    }

    public static void main(String[] args) {
        try {
            FileInputStream in=new FileInputStream(new File("C:\\Users\\DragonGao\\Pictures\\io.png"));
            FTPClient ftpClient = getFTPClient("39.105.189.154", 12996, "power", "123456");
            boolean flag = uploadFile( ftpClient,"/image_upload","", "io1.png", in);
            System.out.println(flag);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}
